package com.microframework.boot.collect.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.microframework.base.data.utils.HttpClientWithAuth;
import com.microframework.base.web.resp.R;
import com.microframework.boot.collect.model.domain.DataSourceConfig;
import com.microframework.boot.collect.model.domain.HttpApi;
import com.microframework.boot.collect.service.IHttpApiService;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class HttpApiServiceImpl implements IHttpApiService {
	
	@Override
	public R<JSONObject> execute(HttpApi httpApi, JSONObject params) {
		return null;
	}

	@Override
	public void executeTask(String dataLogId, String taskId, JSONObject flow) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public JSONObject check(DataSourceConfig dataSourceConfig) throws Exception {
	    // 1. 安全获取连接配置
	    if (dataSourceConfig == null || dataSourceConfig.getConnectionConfig() == null) {
	    	throw new Exception("配置信息不存在.");
	    }

	    try {
	        JSONObject connectionConfig = JSON.parseObject(dataSourceConfig.getConnectionConfig());
			HttpClientWithAuth clientWithAuth=new HttpClientWithAuth();
			
			List<JSONObject> headers = JSON.parseObject(connectionConfig.getString("headers"), new TypeReference<List<JSONObject>>() {});
			List<JSONObject> queryParams = JSON.parseObject(connectionConfig.getString("queryParams"), new TypeReference<List<JSONObject>>() {});

			return clientWithAuth.post(dataSourceConfig, connectionConfig.getJSONObject("connection"), 
					connectionConfig.getJSONObject("authorization")
					, headers, queryParams, connectionConfig.getJSONObject("body"),  connectionConfig.getJSONObject("result"));
	    } catch (Exception e) {
	    	throw e;
	    }
	}


}
